<!--
  题目编辑器
  支持多种题型的创建和编辑
-->
<template>
  <div class="question-editor">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button :icon="ArrowLeft" @click="goBack">返回</el-button>
        <h2>{{ isEdit ? '编辑题目' : '创建题目' }}</h2>
      </div>
      <div class="header-right">
        <el-button @click="handlePreview" :icon="View">预览</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEdit ? '保存修改' : '创建题目' }}
        </el-button>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="editor-content">
      <el-row :gutter="24">
        <!-- 左侧编辑区 -->
        <el-col :span="16">
          <el-card class="editor-card">
            <template #header>
              <span>题目内容</span>
            </template>

            <el-form
              ref="formRef"
              :model="formData"
              :rules="formRules"
              label-width="100px"
            >
              <!-- 基本信息 -->
              <div class="form-section">
                <h4>基本信息</h4>

                <el-form-item label="题目类型" prop="question_type">
                  <el-select
                    v-model="formData.question_type"
                    placeholder="请选择题目类型"
                    :disabled="isEdit"
                    @change="handleTypeChange"
                  >
                    <el-option label="单选题" value="single_choice" />
                    <el-option label="多选题" value="multiple_choice" />
                    <el-option label="判断题" value="true_false" />
                    <el-option label="填空题" value="fill_blank" />
                    <el-option label="简答题" value="short_answer" />
                    <el-option label="编程题" value="programming" />
                  </el-select>
                </el-form-item>

                <el-form-item label="题目标题" prop="title">
                  <el-input
                    v-model="formData.title"
                    placeholder="请输入题目标题"
                    maxlength="200"
                    show-word-limit
                  />
                </el-form-item>

                <el-form-item label="题目内容" prop="content">
                  <el-input
                    v-model="formData.content"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入题目内容，支持HTML格式"
                  />
                  <div class="form-tip">
                    支持 HTML 标签，可以使用 &lt;strong&gt; 加粗 &lt;/strong&gt;、
                    &lt;em&gt; 斜体 &lt;/em&gt;、&lt;code&gt; 代码 &lt;/code&gt; 等格式
                  </div>
                </el-form-item>

                <el-form-item label="难度" prop="difficulty">
                  <el-radio-group v-model="formData.difficulty">
                    <el-radio label="easy">简单</el-radio>
                    <el-radio label="medium">中等</el-radio>
                    <el-radio label="hard">困难</el-radio>
                  </el-radio-group>
                </el-form-item>

                <el-form-item label="分值" prop="points">
                  <el-input-number
                    v-model="formData.points"
                    :min="1"
                    :max="100"
                    :step="1"
                  /> 分
                </el-form-item>

                <el-form-item label="所属题库" prop="question_bank">
                  <el-select
                    v-model="formData.question_bank"
                    placeholder="请选择题库"
                    filterable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="bank in questionBanks"
                      :key="bank.id"
                      :label="bank.name"
                      :value="bank.id"
                    />
                  </el-select>
                </el-form-item>

                <el-form-item label="标签" prop="tags">
                  <el-select
                    v-model="formData.tags"
                    multiple
                    filterable
                    allow-create
                    placeholder="请选择或输入标签"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="tag in availableTags"
                      :key="tag"
                      :label="tag"
                      :value="tag"
                    />
                  </el-select>
                </el-form-item>
              </div>

              <!-- 选择题选项 -->
              <div
                v-if="isChoiceQuestion"
                class="form-section"
              >
                <h4>选项设置</h4>

                <div
                  v-for="(option, index) in formData.options"
                  :key="index"
                  class="option-item"
                >
                  <el-form-item
                    :label="`选项 ${String.fromCharCode(65 + index)}`"
                    :prop="`options.${index}`"
                    :rules="{ required: true, message: '请输入选项内容', trigger: 'blur' }"
                  >
                    <div class="option-input-group">
                      <el-input
                        v-model="formData.options[index]"
                        :placeholder="`请输入选项 ${String.fromCharCode(65 + index)} 内容`"
                        class="option-input"
                      />
                      <el-button
                        type="danger"
                        :icon="Delete"
                        @click="removeOption(index)"
                        v-if="formData.options.length > 2"
                        text
                      />
                    </div>
                  </el-form-item>
                </div>

                <el-form-item>
                  <el-button
                    type="primary"
                    :icon="Plus"
                    @click="addOption"
                    :disabled="formData.options.length >= 8"
                  >
                    添加选项
                  </el-button>
                  <span class="form-tip">
                    最多支持8个选项
                  </span>
                </el-form-item>

                <el-form-item label="正确答案" prop="correct_answer">
                  <!-- 单选题答案 -->
                  <el-radio-group
                    v-if="formData.question_type === 'single_choice'"
                    v-model="formData.correct_answer"
                  >
                    <el-radio
                      v-for="(option, index) in formData.options"
                      :key="index"
                      :label="index"
                    >
                      {{ String.fromCharCode(65 + index) }}. {{ option }}
                    </el-radio>
                  </el-radio-group>

                  <!-- 多选题答案 -->
                  <el-checkbox-group
                    v-else-if="formData.question_type === 'multiple_choice'"
                    v-model="formData.correct_answer"
                  >
                    <el-checkbox
                      v-for="(option, index) in formData.options"
                      :key="index"
                      :label="index"
                    >
                      {{ String.fromCharCode(65 + index) }}. {{ option }}
                    </el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
              </div>

              <!-- 判断题答案 -->
              <div
                v-if="formData.question_type === 'true_false'"
                class="form-section"
              >
                <h4>答案设置</h4>

                <el-form-item label="正确答案" prop="correct_answer">
                  <el-radio-group v-model="formData.correct_answer">
                    <el-radio label="true">正确</el-radio>
                    <el-radio label="false">错误</el-radio>
                  </el-radio-group>
                </el-form-item>
              </div>

              <!-- 填空题答案 -->
              <div
                v-if="formData.question_type === 'fill_blank'"
                class="form-section"
              >
                <h4>答案设置</h4>

                <el-form-item label="正确答案" prop="correct_answer">
                  <el-input
                    v-model="formData.correct_answer"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入正确答案，多个答案用分号(;)分隔"
                  />
                  <div class="form-tip">
                    如有多个答案，请用分号分隔，如：答案1;答案2;答案3
                  </div>
                </el-form-item>
              </div>

              <!-- 简答题答案 -->
              <div
                v-if="formData.question_type === 'short_answer'"
                class="form-section"
              >
                <h4>参考答案</h4>

                <el-form-item label="参考答案" prop="correct_answer">
                  <el-input
                    v-model="formData.correct_answer"
                    type="textarea"
                    :rows="6"
                    placeholder="请输入参考答案"
                  />
                </el-form-item>
              </div>

              <!-- 编程题答案 -->
              <div
                v-if="formData.question_type === 'programming'"
                class="form-section"
              >
                <h4>答案设置</h4>

                <el-form-item label="测试用例">
                  <div
                    v-for="(testCase, index) in testCases"
                    :key="index"
                    class="test-case-item"
                  >
                    <el-card class="test-case-card">
                      <template #header>
                        <div class="test-case-header">
                          <span>测试用例 {{ index + 1 }}</span>
                          <el-button
                            type="danger"
                            :icon="Delete"
                            @click="removeTestCase(index)"
                            text
                            size="small"
                          />
                        </div>
                      </template>

                      <el-form-item label="输入">
                        <el-input
                          v-model="testCase.input"
                          type="textarea"
                          :rows="2"
                          placeholder="请输入测试输入"
                        />
                      </el-form-item>

                      <el-form-item label="期望输出">
                        <el-input
                          v-model="testCase.expected_output"
                          type="textarea"
                          :rows="2"
                          placeholder="请输入期望输出"
                        />
                      </el-form-item>
                    </el-card>
                  </div>

                  <el-button
                    type="primary"
                    :icon="Plus"
                    @click="addTestCase"
                  >
                    添加测试用例
                  </el-button>
                </el-form-item>
              </div>

              <!-- 解析说明 -->
              <div class="form-section">
                <h4>解析说明</h4>

                <el-form-item label="解析" prop="explanation">
                  <el-input
                    v-model="formData.explanation"
                    type="textarea"
                    :rows="4"
                    placeholder="请输入题目解析说明（可选）"
                  />
                </el-form-item>
              </div>
            </el-form>
          </el-card>
        </el-col>

        <!-- 右侧预览区 -->
        <el-col :span="8">
          <el-card class="preview-card">
            <template #header>
              <div class="preview-header">
                <span>题目预览</span>
                <el-button
                  text
                  :icon="Refresh"
                  @click="refreshPreview"
                  size="small"
                >
                  刷新
                </el-button>
              </div>
            </template>

            <div class="question-preview">
              <div class="preview-title">{{ formData.title || '题目标题' }}</div>

              <div class="preview-content">
                <div v-html="formData.content || '题目内容'" />
              </div>

              <!-- 选择题预览 -->
              <div
                v-if="isChoiceQuestion && formData.options.length > 0"
                class="preview-options"
              >
                <div
                  v-for="(option, index) in formData.options"
                  :key="index"
                  class="preview-option"
                >
                  {{ String.fromCharCode(65 + index) }}. {{ option }}
                </div>
              </div>

              <!-- 标签预览 -->
              <div v-if="formData.tags && formData.tags.length > 0" class="preview-tags">
                <el-tag
                  v-for="tag in formData.tags"
                  :key="tag"
                  size="small"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>

              <div class="preview-meta">
                <el-tag :type="getDifficultyType(formData.difficulty)" size="small">
                  {{ getDifficultyText(formData.difficulty) }}
                </el-tag>
                <span class="preview-points">{{ formData.points }} 分</span>
              </div>
            </div>
          </el-card>

          <!-- AI助手 -->
          <el-card class="ai-assistant-card">
            <template #header>
              <div class="ai-header">
                <span>AI 助手</span>
                <el-icon class="ai-icon"><MagicStick /></el-icon>
              </div>
            </template>

            <div class="ai-tools">
              <el-button
                type="primary"
                plain
                :icon="MagicStick"
                @click="generateQuestion"
                :loading="aiGenerating"
                style="width: 100%"
              >
                {{ aiGenerating ? '生成中...' : 'AI生成题目' }}
              </el-button>

              <el-button
                type="success"
                plain
                :icon="Edit"
                @click="enhanceQuestion"
                :loading="aiEnhancing"
                style="width: 100%; margin-top: 8px"
              >
                {{ aiEnhancing ? '优化中...' : 'AI优化内容' }}
              </el-button>

              <el-button
                type="warning"
                plain
                :icon="Document"
                @click="generateExplanation"
                :loading="aiExplaining"
                style="width: 100%; margin-top: 8px"
              >
                {{ aiExplaining ? '生成中...' : 'AI生成解析' }}
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 题目预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="题目预览"
      width="800px"
    >
      <div class="preview-dialog-content">
        <h3>{{ formData.title }}</h3>
        <div class="preview-content" v-html="formData.content" />

        <div v-if="isChoiceQuestion && formData.options.length > 0">
          <h4>选项：</h4>
          <div
            v-for="(option, index) in formData.options"
            :key="index"
            class="preview-option"
          >
            {{ String.fromCharCode(65 + index) }}. {{ option }}
          </div>
        </div>

        <div class="preview-answer">
          <h4>正确答案：</h4>
          <div v-if="isChoiceQuestion">
            <span v-if="formData.question_type === 'single_choice'">
              {{ String.fromCharCode(65 + formData.correct_answer) }}
            </span>
            <div v-else>
              <el-tag
                v-for="answer in formData.correct_answer"
                :key="answer"
                style="margin-right: 8px"
              >
                {{ String.fromCharCode(65 + answer) }}
              </el-tag>
            </div>
          </div>
          <div v-else>
            {{ formData.correct_answer }}
          </div>
        </div>

        <div v-if="formData.explanation" class="preview-explanation">
          <h4>解析：</h4>
          <div v-html="formData.explanation" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  ArrowLeft,
  View,
  Plus,
  Delete,
  Refresh,
  MagicStick,
  Edit,
  Document
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores'
import { questionApi } from '@/api/questions'
import { aiApi } from '@/api/ai'
import type { Question } from '@/types'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const formRef = ref()
const saving = ref(false)
const questionBanks = ref([])
const availableTags = ref([])
const showPreviewDialog = ref(false)

// AI相关状态
const aiGenerating = ref(false)
const aiEnhancing = ref(false)
const aiExplaining = ref(false)

// 表单数据
const formData = reactive({
  title: '',
  content: '',
  question_type: 'single_choice',
  difficulty: 'medium',
  points: 5,
  question_bank: null,
  tags: [],
  options: ['', ''],
  correct_answer: null,
  explanation: ''
})

// 测试用例（编程题用）
const testCases = ref([])

// 是否为编辑模式
const isEdit = computed(() => !!route.params.id)

// 是否为选择题
const isChoiceQuestion = computed(() => {
  return ['single_choice', 'multiple_choice'].includes(formData.question_type)
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入题目标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入题目内容', trigger: 'blur' }
  ],
  question_type: [
    { required: true, message: '请选择题目类型', trigger: 'change' }
  ],
  difficulty: [
    { required: true, message: '请选择难度', trigger: 'change' }
  ],
  points: [
    { required: true, message: '请输入分值', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '分值必须在1-100之间', trigger: 'blur' }
  ],
  question_bank: [
    { required: true, message: '请选择题库', trigger: 'change' }
  ],
  correct_answer: [
    { required: true, message: '请设置正确答案', trigger: 'change' }
  ]
}

// 获取难度类型
const getDifficultyType = (difficulty: string) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

const getDifficultyText = (difficulty: string) => {
  const texts = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return texts[difficulty] || difficulty
}

// 题型变化处理
const handleTypeChange = (type: string) => {
  // 重置答案
  formData.correct_answer = type === 'multiple_choice' ? [] : null

  // 设置默认选项数量
  if (type === 'single_choice' || type === 'multiple_choice') {
    if (formData.options.length < 2) {
      formData.options = ['', '']
    }
  }
}

// 添加选项
const addOption = () => {
  if (formData.options.length < 8) {
    formData.options.push('')
  }
}

// 删除选项
const removeOption = (index: number) => {
  if (formData.options.length > 2) {
    formData.options.splice(index, 1)
    // 调整正确答案
    if (formData.question_type === 'single_choice' && formData.correct_answer === index) {
      formData.correct_answer = null
    } else if (formData.question_type === 'multiple_choice') {
      const answerIndex = formData.correct_answer.indexOf(index)
      if (answerIndex > -1) {
        formData.correct_answer.splice(answerIndex, 1)
      }
    }
  }
}

// 添加测试用例
const addTestCase = () => {
  testCases.value.push({
    input: '',
    expected_output: ''
  })
}

// 删除测试用例
const removeTestCase = (index: number) => {
  testCases.value.splice(index, 1)
}

// 预览题目
const handlePreview = () => {
  showPreviewDialog.value = true
}

// 刷新预览
const refreshPreview = () => {
  ElMessage.success('预览已刷新')
}

// 返回
const goBack = () => {
  router.back()
}

// 保存题目
const handleSave = async () => {
  if (!formRef.value) return

  try {
    saving.value = true
    await formRef.value.validate()

    const questionData = {
      ...formData,
      correct_answer: Array.isArray(formData.correct_answer)
        ? formData.correct_answer
        : formData.correct_answer
    }

    if (formData.question_type === 'programming') {
      questionData.test_cases = testCases.value
    }

    if (isEdit.value) {
      await questionApi.updateQuestion(route.params.id as string, questionData)
      ElMessage.success('题目修改成功')
    } else {
      await questionApi.createQuestion(questionData)
      ElMessage.success('题目创建成功')
    }

    router.push('/questions/questions')
  } catch (error: any) {
    console.error('保存题目失败:', error)
    ElMessage.error(error.message || '保存失败，请检查输入')
  } finally {
    saving.value = false
  }
}

// AI生成题目
const generateQuestion = async () => {
  try {
    aiGenerating.value = true
    const response = await aiApi.generateQuestions({
      subject: '通用',
      topic: formData.title || '自动生成',
      question_type: formData.question_type as any,
      difficulty: formData.difficulty as any,
      count: 1
    })

    if (response.success && response.questions.length > 0) {
      const question = response.questions[0]
      formData.title = question.title
      formData.content = question.content
      if (question.options) {
        formData.options = question.options
      }
      formData.correct_answer = question.correct_answer
      formData.explanation = question.explanation

      ElMessage.success('AI题目生成成功')
    }
  } catch (error) {
    console.error('AI生成题目失败:', error)
    ElMessage.error('AI生成失败，请重试')
  } finally {
    aiGenerating.value = false
  }
}

// AI优化题目
const enhanceQuestion = async () => {
  try {
    aiEnhancing.value = true
    // TODO: 实现AI优化逻辑
    await new Promise(resolve => setTimeout(resolve, 2000))
    ElMessage.success('AI优化完成')
  } catch (error) {
    ElMessage.error('AI优化失败')
  } finally {
    aiEnhancing.value = false
  }
}

// AI生成解析
const generateExplanation = async () => {
  try {
    aiExplaining.value = true
    // TODO: 实现AI生成解析逻辑
    await new Promise(resolve => setTimeout(resolve, 2000))
    formData.explanation = '这是AI生成的解析内容...'
    ElMessage.success('解析生成成功')
  } catch (error) {
    ElMessage.error('解析生成失败')
  } finally {
    aiExplaining.value = false
  }
}

// 加载题库列表
const loadQuestionBanks = async () => {
  try {
    // TODO: 调用实际的题库API
    questionBanks.value = [
      { id: 1, name: '数学题库' },
      { id: 2, name: '语文题库' },
      { id: 3, name: '英语题库' }
    ]
  } catch (error) {
    console.error('加载题库失败:', error)
  }
}

// 加载可用标签
const loadAvailableTags = async () => {
  try {
    // TODO: 调用实际的标签API
    availableTags.value = ['基础', '进阶', '高级', '算法', '数据结构']
  } catch (error) {
    console.error('加载标签失败:', error)
  }
}

// 加载题目详情（编辑模式）
const loadQuestionDetail = async () => {
  if (!isEdit.value) return

  try {
    const response = await questionApi.getQuestion(route.params.id as string)
    const question = response.data

    // 填充表单数据
    Object.assign(formData, {
      ...question,
      correct_answer: Array.isArray(question.correct_answer)
        ? question.correct_answer
        : question.correct_answer
    })

    if (question.question_type === 'programming' && question.test_cases) {
      testCases.value = question.test_cases
    }
  } catch (error) {
    console.error('加载题目详情失败:', error)
    ElMessage.error('加载题目失败')
    goBack()
  }
}

// 初始化
onMounted(async () => {
  await loadQuestionBanks()
  await loadAvailableTags()
  if (isEdit.value) {
    await loadQuestionDetail()
  }
})
</script>

<style scoped lang="scss">
.question-editor {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;

      h2 {
        margin: 0;
        color: var(--el-text-color-primary);
      }
    }

    .header-right {
      display: flex;
      gap: 12px;
    }
  }

  .editor-content {
    .editor-card {
      .form-section {
        margin-bottom: 32px;

        h4 {
          margin: 0 0 16px 0;
          color: var(--el-text-color-primary);
          font-size: 16px;
          font-weight: 600;
          border-bottom: 2px solid var(--el-color-primary);
          padding-bottom: 8px;
        }

        .form-tip {
          font-size: 12px;
          color: var(--el-text-color-placeholder);
          margin-top: 4px;
        }

        .option-item {
          .option-input-group {
            display: flex;
            gap: 8px;
            align-items: center;

            .option-input {
              flex: 1;
            }
          }
        }

        .test-case-item {
          margin-bottom: 16px;

          .test-case-card {
            .test-case-header {
              display: flex;
              justify-content: space-between;
              align-items: center;
            }
          }
        }
      }
    }

    .preview-card {
      .preview-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .question-preview {
        .preview-title {
          font-size: 18px;
          font-weight: 600;
          margin-bottom: 12px;
          color: var(--el-text-color-primary);
        }

        .preview-content {
          margin-bottom: 16px;
          line-height: 1.6;
          color: var(--el-text-color-regular);
        }

        .preview-options {
          margin-bottom: 16px;

          .preview-option {
            margin-bottom: 8px;
            padding: 8px;
            background: var(--el-fill-color-light);
            border-radius: 4px;
          }
        }

        .preview-tags {
          margin-bottom: 16px;

          .tag-item {
            margin-right: 8px;
            margin-bottom: 4px;
          }
        }

        .preview-meta {
          display: flex;
          align-items: center;
          gap: 12px;

          .preview-points {
            font-size: 14px;
            color: var(--el-color-primary);
            font-weight: 500;
          }
        }
      }
    }

    .ai-assistant-card {
      margin-top: 16px;

      .ai-header {
        display: flex;
        align-items: center;
        gap: 8px;

        .ai-icon {
          color: var(--el-color-primary);
        }
      }

      .ai-tools {
        .el-button {
          margin-bottom: 8px;
        }
      }
    }
  }

  .preview-dialog-content {
    h3 {
      margin-bottom: 16px;
      color: var(--el-text-color-primary);
    }

    .preview-content {
      margin-bottom: 20px;
      line-height: 1.6;
    }

    .preview-option {
      margin-bottom: 8px;
      padding: 8px;
      background: var(--el-fill-color-light);
      border-radius: 4px;
    }

    .preview-answer,
    .preview-explanation {
      margin-top: 20px;

      h4 {
        margin-bottom: 8px;
        color: var(--el-text-color-primary);
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .question-editor {
    .editor-content {
      .el-col {
        margin-bottom: 16px;
      }
    }
  }
}
</style>
